package com.piece.admin.service;

import com.piece.admin.model.TbSysConfig;
import com.piece.admin.repository.TbSysConfigRepository;
import com.piece.core.framework.enums.sql.SqlKey;
import com.piece.core.jpa.repository.BaseService;
import com.piece.core.framework.support.bootstrap.Order;
import com.piece.core.framework.util.string.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class TbSysConfigService extends BaseService<TbSysConfig, Long> {

    @Resource
    private TbSysConfigRepository tbSysConfigRepository;

    @PostConstruct
    public void initRepository() {
        setRepository(tbSysConfigRepository);
    }

    /**
     * 根据configKey查询
     */
    public TbSysConfig findByConfigKey(String configKey) {
        return findByConfigKey(configKey, null);
    }

    /**
     * 根据configKey查询
     */
    public TbSysConfig findByConfigKey(String configKey, String configType) {
        HashMap<String, Object> condition = new HashMap<>();
        condition.put("configKey", configKey);
        if (StringUtil.isNotEmpty(configType)) {
            condition.put("configType", configType);
        }
        return tbSysConfigRepository.findOneByCondition(condition);
    }

    @Override
    protected List<Order> generateDefaultOrder() {
        List<Order> orders = new ArrayList<>();
        orders.add(new Order("configId", SqlKey.ASC));
        return orders;
    }

    /**
     * 校验参数名称是否唯一
     *
     * @param configName
     * @return true: 通过 false: 重复
     */
    public boolean checkConfigNameUnique(Long configId, String configName) {
        String hql = "from TbSysConfig where configName = ?0";
        Object[] params = new Object[]{configName};
        if (null != configId) {
            hql = "from TbSysConfig where configId != ?0 and configName = ?1";
            params = new Object[]{configId, configName};
        }
        long count = tbSysConfigRepository.count(hql, params, true);
        return count <= 0;
    }

    /**
     * 校验参数KEY是否唯一
     *
     * @param configKey
     * @return true: 通过 false: 重复
     */
    public boolean checkConfigKeyUnique(Long configId, String configKey) {
        String hql = "from TbSysConfig where configKey = ?0";
        Object[] params = new Object[]{configKey};
        if (null != configId) {
            hql = "from TbSysConfig where configId != ?0 and configKey = ?1";
            params = new Object[]{configId, configKey};
        }
        long count = tbSysConfigRepository.count(hql, params, true);
        return count <= 0;
    }
}
